package com.goods.business.service.imp;

import com.goods.business.mapper.*;
import com.goods.business.service.BusinessService;
import com.goods.common.model.business.*;
import com.goods.common.utils.CategoryTreeBuilder;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private OutStockMapper outStockMapper;
    @Autowired
    private OutStockInfoMapper outStockInfoMapper;
    @Autowired
    private HealthMapper healthMapper;

    /**
     * 加载分类数据
     *
     * @param pageNum  页数, 当前是第几页
     * @param pageSize 每页记录数
     * @return
     */
    @Override
    public PageVO<ProductCategoryTreeNodeVO> categoryTree(Integer pageNum, Integer pageSize) {

        //1. 查询全部的分类数据
        List<ProductCategoryTreeNodeVO> productCategoryTreeNodeVOList = getProductCategoryTreeNodeVOS();

        //调用工具类获取三级分类
        List<ProductCategoryTreeNodeVO> productCategoryTreeNodeVOS = CategoryTreeBuilder.build(productCategoryTreeNodeVOList);

        if (pageNum==null || pageSize==null){
            return new PageVO<>(productCategoryTreeNodeVOS.size(), productCategoryTreeNodeVOS);
        }

        List<ProductCategoryTreeNodeVO> page = ListPageUtils.page(productCategoryTreeNodeVOS, pageSize, pageNum);

        return new PageVO<>(productCategoryTreeNodeVOS.size(), page);
    }

    /**
     * 视图对象转换
     *
     * @return
     */
    private List<ProductCategoryTreeNodeVO> getProductCategoryTreeNodeVOS() {
        List<ProductCategory> productCategories = productCategoryMapper.selectAll();
        return productCategories.stream().map(productCategory -> {
            ProductCategoryTreeNodeVO productCategoryTreeNodeVO = new ProductCategoryTreeNodeVO();
            BeanUtils.copyProperties(productCategory, productCategoryTreeNodeVO);
            return productCategoryTreeNodeVO;
        }).collect(Collectors.toList());
    }


    /**
     * 加载父级分类数据
     *
     * @return
     */
    @Override
    public List<ProductCategoryTreeNodeVO> getParentCategoryTree() {
        List<ProductCategoryTreeNodeVO> productCategoryTreeNodeVOS = this.getProductCategoryTreeNodeVOS();
        return CategoryTreeBuilder.buildParent(productCategoryTreeNodeVOS);
    }

    /**
     * 添加分类
     *
     * @param productCategoryVO
     */
    @Override
    public void add(ProductCategoryVO productCategoryVO) {
        ProductCategory productCategory = getProductCategory(productCategoryVO);
        productCategory.setCreateTime(new Date());
        productCategory.setModifiedTime(new Date());
        productCategoryMapper.insertSelective(productCategory);
    }

    /**
     * 将 ProductCategoryVO 转为 ProductCategory
     *
     * @param productCategoryVO
     * @return
     */
    private ProductCategory getProductCategory(ProductCategoryVO productCategoryVO) {
        ProductCategory productCategory = new ProductCategory();
        BeanUtils.copyProperties(productCategoryVO, productCategory);
        return productCategory;
    }

    /**
     * 编辑
     *
     * @param id
     * @return
     */
    @Override
    public ProductCategoryVO edit(Long id) {
        ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(id);
        ProductCategoryVO productCategoryVO = getProductCategoryVO(productCategory);
        return productCategoryVO;
    }

    /**
     * 将 ProductCategory 转为 ProductCategoryVO
     *
     * @param productCategory
     * @return
     */
    private ProductCategoryVO getProductCategoryVO(ProductCategory productCategory) {
        ProductCategoryVO productCategoryVO = new ProductCategoryVO();
        BeanUtils.copyProperties(productCategory, productCategoryVO);
        return productCategoryVO;
    }

    /**
     * 修改
     *
     * @param id
     * @param productCategoryVO
     */
    @Override
    public void update(Long id, ProductCategoryVO productCategoryVO) {
        ProductCategory productCategory = this.getProductCategory(productCategoryVO);
        productCategory.setModifiedTime(new Date());
        productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    /**
     * 删除分类：如果有子类的话，一起删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        //获取全部id，批量删除
        List<Long> idList = new ArrayList();
        idList.add(id);

        ProductCategory productCategory = new ProductCategory();
        productCategory.setPid(id);
        List<ProductCategory> productCategoryList1 = productCategoryMapper.select(productCategory);
        if (!CollectionUtils.isEmpty(productCategoryList1)) {
            for (ProductCategory category : productCategoryList1) {
                idList.add(category.getId());
                productCategory.setPid(category.getId());
                List<ProductCategory> productCategoryList2 = productCategoryMapper.select(productCategory);
                productCategoryList2.forEach(productCategory2 -> {
                    idList.add(productCategory2.getId());
                });
            }
        }

        //删除id分类的数据
        productCategoryMapper.deleteCategory(idList);
    }

    /**
     * 带条件查询的物资来源分页列表展示
     *
     * @param pageNum
     * @param pageSize
     * @param supplierVO
     * @return
     */
    @Override
    public PageVO<SupplierVO> findSupplierList(Integer pageNum, Integer pageSize, SupplierVO supplierVO) {

        List<Supplier> supplierList = supplierMapper.findSupplierList(supplierVO);
        List<SupplierVO> supplierVOList = supplierList.stream().map(supplier -> {
            SupplierVO vo = new SupplierVO();
            BeanUtils.copyProperties(supplier, vo);
            return vo;
        }).collect(Collectors.toList());

        List<SupplierVO> rows = ListPageUtils.page(supplierVOList, pageSize, pageNum);

        return new PageVO<>(supplierList.size(), rows);
    }

    /**
     * 添加物资来源
     *
     * @param supplierVO
     */
    @Override
    public void supplierAdd(SupplierVO supplierVO) {
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierVO, supplier);
        supplier.setCreateTime(new Date());
        supplier.setModifiedTime(new Date());
        supplierMapper.insertSelective(supplier);
    }

    /**
     * 编辑物资来源
     *
     * @param id
     * @return
     */
    @Override
    public SupplierVO supplierEdit(Long id) {
        Supplier supplier = supplierMapper.selectByPrimaryKey(id);
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier, supplierVO);
        return supplierVO;
    }

    /**
     * 更新用户物资来源
     *
     * @param id
     * @param supplierVO
     */
    @Override
    public void supplierUpdate(Long id, SupplierVO supplierVO) {
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierVO, supplier);
        supplier.setModifiedTime(new Date());
        supplierMapper.updateByPrimaryKeySelective(supplier);
    }

    /**
     * 删除来源
     *
     * @param id
     */
    @Override
    public void supplierDelete(Long id) {
        supplierMapper.deleteByPrimaryKey(id);
    }

    /**
     * 加载物资列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param categoryId
     * @param supplier
     * @param status
     * @return
     */
    @Override
    public PageVO<ProductVO> findProductList(Integer pageNum, Integer pageSize, String name, Long categoryId, String supplier, Integer status) {

        List<Product> productList = productMapper.findProductList(name, categoryId, supplier, status);
        List<ProductVO> productVOList = productList.stream().map(product -> {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            return productVO;
        }).collect(Collectors.toList());

        List<ProductVO> page = ListPageUtils.page(productVOList, pageSize, pageNum);

        return new PageVO<>(productVOList.size(), page);
    }

    /**
     * 添加物资
     *
     * @param productVO
     */
    @Override
    public void productAdd(ProductVO productVO) {
        Product product = new Product();
        BeanUtils.copyProperties(productVO, product);
        product.setPNum(UUID.randomUUID().toString().substring(0, 32));
        product.setCreateTime(new Date());
        product.setModifiedTime(new Date());

        product.setOneCategoryId(productVO.getCategoryKeys()[0]);
        product.setTwoCategoryId(productVO.getCategoryKeys()[1]);
        product.setThreeCategoryId(productVO.getCategoryKeys()[2]);

        product.setStatus(2);
        productMapper.insertSelective(product);
    }

    /**
     * 编辑物资
     *
     * @param id
     * @return
     */
    @Override
    public ProductVO productEdit(Long id) {
        Product product = productMapper.selectByPrimaryKey(id);
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product, productVO);
        return productVO;
    }

    /**
     * 更新物资
     *
     * @param id
     * @param productVO
     */
    @Override
    public void productUpdate(Long id, ProductVO productVO) {
        Product product = new Product();
        BeanUtils.copyProperties(productVO, product);
        product.setModifiedTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 移除回收站
     *
     * @param id
     */
    @Override
    public void productRemove(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(1);
        product.setModifiedTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 从回收站恢复
     *
     * @param id
     */
    @Override
    public void productBack(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(0);
        product.setModifiedTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 删除物资
     *
     * @param id
     */
    @Override
    public void productDelete(Long id) {
        productMapper.deleteByPrimaryKey(id);
    }

    /**
     * 物资添加审核
     *
     * @param id
     */
    @Override
    public void productPublish(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(0);
        product.setModifiedTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 入库单（入库记录）数据分页列表展示
     *
     * @param pageNum
     * @param pageSize
     * @param inStockVO
     * @return
     */
    @Override
    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {

        List<InStockVO> inStockVOList = inStockMapper.findInStockList(inStockVO);

        List<InStockVO> page = ListPageUtils.page(inStockVOList, pageSize, pageNum);

        return new PageVO<>(inStockVOList.size(), page);
    }

    /**
     * 查看入库单明细
     *
     * @param id
     * @param pageNum
     * @return
     */
    @Override
    public InStockDetailVO inStockDetail(Long id, Integer pageNum) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();

        InStock inStock = inStockMapper.selectByPrimaryKey(id);

        List<InStockItemVO> itemVOS = inStockInfoMapper.inStockDetail(inStock.getInNum());
        inStockDetailVO.setItemVOS(itemVOS);
        inStockDetailVO.setTotal(itemVOS.size());

        inStockDetailVO.setInNum(inStock.getInNum());
        inStockDetailVO.setStatus(inStock.getStatus());
        inStockDetailVO.setType(inStock.getType());
        inStockDetailVO.setOperator(inStock.getOperator());

        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier, supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);

        return inStockDetailVO;
    }

    /**
     * 移除回收站
     *
     * @param id
     */
    @Override
    public void inStockRemove(Long id) {
        InStock inStock = new InStock();
        inStock.setStatus(1);
        inStock.setModified(new Date());
        inStockMapper.updateByPrimaryKeySelective(inStock);
    }

    /**
     * 从回收站恢复
     *
     * @param id
     */
    @Override
    public void inStockBack(Long id) {
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock.setStatus(0);
        inStock.setModified(new Date());
        inStockMapper.updateByPrimaryKeySelective(inStock);
    }

    /**
     * 物资入库审核
     *
     * @param id
     */
    @Override
    public void inStockPublish(Long id) {
        //1. 查询inStockInfoList集合
        List<InStockInfo> inStockInfoList = inStockInfoMapper.inStockPublish(id);

        for (InStockInfo inStockInfo : inStockInfoList) {
            //根据商品编号查找商品
            ProductStock productStock = new ProductStock();
            productStock.setPNum(inStockInfo.getPNum());
            ProductStock result = productStockMapper.selectOne(productStock);

            if (null != result) {
                //已经有该商品， 只需修改数量
                result.setStock(result.getStock() + inStockInfo.getProductNumber());
                productStockMapper.updateByPrimaryKeySelective(productStock);
            } else {
                //没有该商品，需要添加
                productStock.setStock(Long.valueOf(inStockInfo.getProductNumber()));
                productStockMapper.insertSelective(productStock);
            }
        }

        //2. 更改入库单状态
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock.setStatus(0);
        inStock.setModified(new Date());
        inStockMapper.updateByPrimaryKeySelective(inStock);
    }

    /**
     * 删除明细
     *
     * @param id
     */
    @Override
    public void inStockDelete(Long id) {
        inStockMapper.deleteByPrimaryKey(id);
    }

    /**
     * 加载来源数据
     *
     * @return
     */
    @Override
    public List<SupplierVO> findAll() {
        return supplierMapper.selectAll().stream().map(supplier -> {
            SupplierVO supplierVO = new SupplierVO();
            BeanUtils.copyProperties(supplier, supplierVO);
            return supplierVO;
        }).collect(Collectors.toList());
    }

    /**
     * 加载商品列表(可入库)
     *
     * @param pageNum
     * @param pageSize
     * @param categorys
     * @return
     */
    @Override
    public PageVO<ProductVO> findProducts(Integer pageNum, Integer pageSize, String categorys) {
        List<Product> productList = null;
        if (!StringUtils.isEmpty(categorys)) {
            String[] split = categorys.split(",");
            if (split.length == 1) {
                productList = productMapper.findProducts(Long.valueOf(split[0]), null, null);
            }
            if (split.length == 2) {
                productList = productMapper.findProducts(Long.valueOf(split[0]), Long.valueOf(split[1]), null);
            }
            if (split.length == 3) {
                productList = productMapper.findProducts(Long.valueOf(split[0]), Long.valueOf(split[1]), Long.valueOf(split[2]));
            }
        } else {
            productList = productMapper.findProducts(null, null, null);
        }

        List<ProductVO> productVOList = productList.stream().map(product -> {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            return productVO;
        }).collect(Collectors.toList());

        List<ProductVO> page = ListPageUtils.page(productVOList, pageSize, pageNum);

        return new PageVO<>(productVOList.size(), page);
    }

    /**
     * 添加入库单
     *
     * @param inStockVO
     */
    @Override
    public void addIntoStock(InStockVO inStockVO) {
        //生成入库编号
        String inNum = UUID.randomUUID().toString().replace("-", "").substring(0, 28);

        //1. 添加物资来源——biz_supplier表        优先添加，后面的添加需要它的主键id
        //根据是否有supplierId判断是新增来源，还是已有来源，没有，添加
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStockVO.getSupplierId());
        if (supplier == null) {
            supplier = new Supplier();
            supplier.setName(inStockVO.getName());
            supplier.setAddress(inStockVO.getAddress());
            supplier.setEmail(inStockVO.getEmail());
            supplier.setPhone(inStockVO.getPhone());
            supplier.setSort(inStockVO.getSort());
            supplier.setContact(inStockVO.getContact());
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            supplierMapper.insertSelective(supplier);
        }

        //2. 添加入库表单——biz_in_stock表
        InStock inStock = new InStock();
        BeanUtils.copyProperties(inStockVO, inStock);
        inStock.setInNum(inNum);
        inStock.setOperator("admin");
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());

        Integer number = inStockVO.getProducts().stream().map(product -> {
            Map prod = (Map) product;
            Integer productNumber = (Integer) prod.get("productNumber");
            return productNumber;
        }).reduce(Integer::sum).get();
        inStock.setProductNumber(number);

        inStock.setSupplierId(supplier.getId());
        inStock.setStatus(2);
        inStockMapper.insertSelective(inStock);

        //3. 添加入库明细表——biz_in_stock_info表

        inStockVO.getProducts().stream().forEach(product -> {
            Map map = (Map) product;
            Long productId = Long.valueOf((Integer) map.get("productId"));
            Integer productNumber = (Integer) map.get("productNumber");

            InStockInfo inStockInfo = new InStockInfo();
            inStockInfo.setInNum(inNum);
            Product product1 = productMapper.selectByPrimaryKey(productId);
            inStockInfo.setPNum(product1.getPNum());
            inStockInfo.setProductNumber(productNumber);
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setModifiedTime(new Date());

            inStockInfoMapper.insertSelective(inStockInfo);
        });
    }

    /**
     * 加载库存信息
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param categorys
     * @return
     */
    @Override
    public PageVO<ProductStockVO> findProductStocks(Integer pageNum, Integer pageSize, String name, String categorys) {
        List<ProductStockVO> productStockVOList = this.findAllStocks(name, categorys);
        List<ProductStockVO> page = ListPageUtils.page(productStockVOList, pageSize, pageNum);
        return new PageVO<>(productStockVOList.size(), page);
    }

    /**
     * 物资所有的库存信息
     *
     * @param name
     * @param categorys
     * @return
     */
    @Override
    public List<ProductStockVO> findAllStocks(String name, String categorys) {
        List<ProductStockVO> productStockVOList = null;
        if (!StringUtils.isEmpty(categorys)) {
            String[] split = categorys.split(",");
            if (split.length == 1) {
                productStockVOList = productStockMapper.findProductStocks(name, Long.valueOf(split[0]), null, null);
            }
            if (split.length == 2) {
                productStockVOList = productStockMapper.findProductStocks(name, Long.valueOf(split[0]), Long.valueOf(split[1]), null);
            }
            if (split.length == 3) {
                productStockVOList = productStockMapper.findProductStocks(name, Long.valueOf(split[0]), Long.valueOf(split[1]), Long.valueOf(split[2]));
            }
        } else {
            productStockVOList = productStockMapper.findProductStocks(name, null, null, null);
        }
        return productStockVOList;
    }

    /**
     * 加载物资去处列表
     *
     * @param pageNum
     * @param pageSize
     * @param address
     * @param contact
     * @param name
     * @return
     */
    @Override
    public PageVO<ConsumerVO> findConsumerList(Integer pageNum, Integer pageSize, String address, String contact, String name) {
        List<Consumer> consumerList = consumerMapper.findConsumerList(address, contact, name);
        List<ConsumerVO> consumerVOList = consumerList.stream().map(consumer -> {
            ConsumerVO consumerVO = new ConsumerVO();
            BeanUtils.copyProperties(consumer, consumerVO);
            return consumerVO;
        }).collect(Collectors.toList());

        List<ConsumerVO> page = ListPageUtils.page(consumerVOList, pageSize, pageNum);

        return new PageVO<>(consumerVOList.size(), page);
    }

    /**
     * 添加物资去处
     *
     * @param consumerVO
     */
    @Override
    public void consumerAdd(ConsumerVO consumerVO) {
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(consumerVO, consumer);
        consumer.setCreateTime(new Date());
        consumer.setModifiedTime(new Date());
        consumerMapper.insertSelective(consumer);
    }

    /**
     * 编辑物资去处
     *
     * @param id
     * @return
     */
    @Override
    public ConsumerVO consumerEdit(Long id) {
        Consumer consumer = consumerMapper.selectByPrimaryKey(id);
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer, consumerVO);
        return consumerVO;
    }

    /**
     * 修改物资去处
     *
     * @param id
     * @param consumerVO
     */
    @Override
    public void consumerUpdate(Long id, ConsumerVO consumerVO) {
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(consumerVO, consumer);
        consumer.setModifiedTime(new Date());
        consumerMapper.updateByPrimaryKeySelective(consumer);
    }

    /**
     * 删除物资去处
     *
     * @param id
     */
    @Override
    public void consumerDelete(Long id) {
        consumerMapper.deleteByPrimaryKey(id);
    }

    /**
     * 出库单（发放记录）数据分页列表展示
     *
     * @param pageNum
     * @param pageSize
     * @param outNum
     * @param type
     * @param status
     * @return
     */
    @Override
    public PageVO<OutStockVO> findOutStockList(Integer pageNum, Integer pageSize, String outNum, Integer type, Integer status) {

        List<OutStockVO> outStockVOList = outStockMapper.findOutStockList(outNum, type, status);

        List<OutStockVO> page = ListPageUtils.page(outStockVOList, pageSize, pageNum);
        return new PageVO<>(outStockVOList.size(), page);
    }

    /**
     * 查看发放单明细
     *
     * @param pageNum
     * @param id
     * @return
     */
    @Override
    public OutStockDetailVO outStockDetail(Integer pageNum, Long id) {
        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();

        OutStock outStock = outStockMapper.selectByPrimaryKey(id);

        List<OutStockItemVO> outStockItemVOList = outStockInfoMapper.outStockDetail(outStock.getOutNum());
        outStockDetailVO.setItemVOS(outStockItemVOList);
        outStockDetailVO.setTotal(outStockItemVOList.size());

        outStockDetailVO.setOutNum(outStock.getOutNum());
        outStockDetailVO.setStatus(outStock.getStatus());
        outStockDetailVO.setType(outStock.getType());
        outStockDetailVO.setOperator(outStock.getOperator());

        Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer, consumerVO);
        outStockDetailVO.setConsumerVO(consumerVO);

        return outStockDetailVO;
    }

    /**
     * 移除回收站
     *
     * @param id
     */
    @Override
    public void outStockRemove(Long id) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(1);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    /**
     * 从回收站恢复
     *
     * @param id
     */
    @Override
    public void outStockBack(Long id) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    /**
     * 删除明细
     *
     * @param id
     */
    @Override
    public void outStockDelete(Long id) {
        outStockMapper.deleteByPrimaryKey(id);
    }

    /**
     * 物资发放审核
     *
     * @param id
     */
    @Override
    public void outStockPublish(Long id) {
        //1. 更新物资库存数量（扣减）
        //(1) 获取OutStockInfo集合
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.outStockPublish(id);
        if (CollectionUtils.isEmpty(outStockInfoList)) {
            return;
        }

        for (OutStockInfo outStockInfo : outStockInfoList) {
            //根据商品编号查询对应的商品库存
            ProductStock productStock = new ProductStock();
            productStock.setPNum(outStockInfo.getPNum());
            ProductStock result = productStockMapper.selectOne(productStock);
            if (result.getStock() >= outStockInfo.getProductNumber()) {
                result.setStock(result.getStock() - outStockInfo.getProductNumber());
                productStockMapper.updateByPrimaryKeySelective(result);
            } else {
                //库存不足
                return;
            }
        }

        //2. 出库单状态转为已发放
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    /**
     * 加载去向数据
     *
     * @return
     */
    @Override
    public List<ConsumerVO> consumerFindAll() {
        return consumerMapper.selectAll().stream().map(consumer -> {
            ConsumerVO consumerVO = new ConsumerVO();
            BeanUtils.copyProperties(consumer, consumerVO);
            return consumerVO;
        }).collect(Collectors.toList());
    }

    /**
     * 创建发放单
     *
     * @param outStockVO
     */
    @Override
    public void addOutStock(OutStockVO outStockVO) {
        String outNum = UUID.randomUUID().toString().replace("-", "").substring(0, 28);

        //1. 添加物资去向表——biz_consumer表
        //根据是否有consumerId判断是新增去向，还是已知去向。
        Consumer consumer = consumerMapper.selectByPrimaryKey(outStockVO.getConsumerId());
        if (null == consumer) {
            consumer = new Consumer();
            BeanUtils.copyProperties(outStockVO, consumer);
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            consumerMapper.insertSelective(consumer);
        }

        //2. 添加出库单表——biz_out_stock表
        OutStock outStock = new OutStock();
        BeanUtils.copyProperties(outStockVO, outStock);
        outStock.setOutNum(outNum);
        outStock.setOperator("admin");
        outStock.setCreateTime(new Date());
        Integer number = outStockVO.getProducts().stream().map(product -> {
            Map prod = (Map) product;
            Integer productNumber = (Integer) prod.get("productNumber");
            return productNumber;
        }).reduce(Integer::sum).get();
        outStock.setProductNumber(number);
        outStock.setConsumerId(consumer.getId());
        outStock.setStatus(2);
        outStockMapper.insertSelective(outStock);

        //3. 添加出库明细表——biz_out_stock_info表
        outStockVO.getProducts().stream().forEach(product -> {
            Map map = (Map) product;
            Long productId = Long.valueOf((Integer) map.get("productId"));
            Integer productNumber = (Integer) map.get("productNumber");

            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setOutNum(outNum);
            Product product1 = productMapper.selectByPrimaryKey(productId);
            outStockInfo.setPNum(product1.getPNum());
            outStockInfo.setProductNumber(productNumber);
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());

            outStockInfoMapper.insertSelective(outStockInfo);
        });
    }

    /**
     * 今日是否已签到
     *
     * @return
     */
    @Override
    public HealthVO isReport() {
        Health health = null;
        try {
            Example example = new Example(Health.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String localDate = LocalDate.now().toString();

            example.createCriteria().andBetween("createTime", sdf.parse(localDate + " 00:00:00"), sdf.parse(localDate + " 24:00:00"));
            health = healthMapper.selectOneByExample(example);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (null != health) {
            HealthVO healthVO = new HealthVO();
            BeanUtils.copyProperties(health, healthVO);
            return healthVO;
        }

        return null;
    }

    /**
     * 打卡
     *
     * @param healthVO
     */
    @Override
    public void report(HealthVO healthVO) {
        Health health = new Health();
        BeanUtils.copyProperties(healthVO, health);
        health.setUserId(5L);
        health.setCreateTime(new Date());
        healthMapper.insertSelective(health);
    }

    /**
     * //打卡历史记录
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageVO<HealthVO> history(Integer pageNum, Integer pageSize) {
        List<HealthVO> healthVOList = healthMapper.selectAll().stream().map(health -> {
            HealthVO healthVO = new HealthVO();
            BeanUtils.copyProperties(health, healthVO);
            return healthVO;
        }).collect(Collectors.toList());

        List<HealthVO> page = ListPageUtils.page(healthVOList, pageSize, pageNum);
        return new PageVO<>(healthVOList.size(), page);
    }
}
